package cae.logic;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

import cae.logic.CaeMessage;
import cae.logic.CaeMessagePublisher;
import cae.logic.CaeMessageStub;
import cae.logic.history.CaeMessageHistory;
import cae.logic.util.CaeClipConfiguration;



public class CaeRemoteMessageListener implements Runnable{

	private ServerSocket socket;
	private boolean stop = false;
	private CaeMessagePublisher pubisher;
	private Logger logger = Logger.getLogger(CaeRemoteMessageListener.class);
	
	public CaeRemoteMessageListener(CaeMessagePublisher pubisher) throws IOException
	{
		this.socket = new ServerSocket(CaeClipConfiguration.getInstance().getIProp(CaeClipConfiguration.PORT));
		this.pubisher = pubisher;
	}
	
	public void run()
	{
		while(!stop)
		{
			Socket csocket;
			try {
				csocket = socket.accept();
				new Thread(new CaeSingleRemoteMessageProcesor(csocket)).start();
			} catch (IOException e) {
				logger.info("Falla al recibir mensaje, es posible que no sea un error:", e);
			}
			

		}
	}
	
	private class CaeSingleRemoteMessageProcesor implements Runnable
	{
		Socket csocket;
		
		private CaeSingleRemoteMessageProcesor(Socket csocket)
		{
			this.csocket = csocket;
		}
		
		public void run()
		{
			try 
			{
				ObjectInputStream ois = new ObjectInputStream(csocket.getInputStream());
				CaeMessageStub stub = (CaeMessageStub) ois.readObject();
				String messageText = stub.getText();
				
				String from = csocket.getInetAddress().getHostName();
	
				CaeMessage message = new CaeMessage(messageText, from);
				
				CaeMessageHistory.getInstance().addMessage(message);
				
				pubisher.publishMessage(new CaeMessage(messageText, from), 10);
			} 
			catch (Exception e)
			{
				logger.debug("Falla al recibir mensaje, es posible que no sea un error:", e);
				// error al recibir mensaje IGNORAR;
				// POR EJEMPLO CUANDO TESTEA CONECCION
			}
		}
		
	}
}
